package com.szewec.ps.ui.tabbar;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONObject;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.szewec.ps.R;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.Enums;
import com.szewec.ps.base.ListBaseAdapter;
import com.szewec.ps.base.SuperViewHolder;
import com.szewec.ps.databinding.FragmentApplicationBinding;
import com.szewec.ps.model.Meta;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.project.ProjectListModel;
import com.szewec.ps.model.project.ProjectMemberListModel;
import com.szewec.ps.myview.BottomShowDialog;
import com.szewec.ps.myview.BottomShowSelectProject;
import com.szewec.ps.ui.project.ProjectEditActivity;
import com.szewec.ps.ui.task.TaskIndexActivity;
import com.szewec.ps.util.DateUtil;
import com.szewec.ps.util.PreferincesContext;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.okhttp.OkHttp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;
import static android.content.ContentValues.TAG;


public class ApplicationFragment extends Fragment {
    private FragmentApplicationBinding binding;

    private MyListDataAdapter _mListDataAdapter;
    private List<ProjectListModel.ProjectModel> dataSource = new ArrayList<>();;

    //总条数
    private Integer TOTAL_COUNTER = -1;
    //页码
    private Integer _pageIndex = 1;
    //每页的条数
    private Integer _pageSize = 12;
    //操作权限
    private JSONObject itemActions = new JSONObject();


    /*private ActivityResultLauncher<Intent> startActivitylaunch;*/

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /*startActivitylaunch = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == RESULT_OK){
                    _pageIndex = 1;
                    binding.lRecyclerView.setNoMore(false);
                    getListDataFromServer();
                }
            }
        });*/

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_application, container, false);
        // 2、获取到视图
        View inflate = binding.getRoot();
        ButterKnife.bind(this, inflate);

        // 请求数据
        getListDataFromServer();

        // 初始化视图
        initView();

        // 请求列表数据
        return inflate;
    }

    private void getListDataFromServer(){
        HashMap<String, Object> param = new HashMap<>();
        param.put("pageIndex", _pageIndex);
        param.put("pageSize", _pageSize);
        OkHttp.get("/tpms-plan-service/api/project/select", param, null, (result -> {
            Log.i(TAG, result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject meta = jsonObject.getJSONObject("meta");
            JSONObject newItemActions = meta.getJSONObject("itemActions");

            ProjectListModel listModel = JSONObject.parseObject(result, ProjectListModel.class);
            Meta metaBean =  listModel.getMeta();
            TOTAL_COUNTER = metaBean.getTotal() != null ? metaBean.getTotal() : -1;
            if(_pageIndex == 1){
                itemActions.clear();
                dataSource.clear();
            }
            if (newItemActions != null){
                itemActions.putAll(newItemActions);
            }
            dataSource.addAll(listModel.getData());
            if(dataSource.size()>0){
                binding.lRecyclerView.setVisibility(View.VISIBLE);
                binding.noDataPrompt.setVisibility(View.GONE);
            }else {
                binding.lRecyclerView.setVisibility(View.GONE);
                binding.noDataPrompt.setVisibility(View.VISIBLE);
            }

            binding.lRecyclerView.refreshComplete(TOTAL_COUNTER);
            _mListDataAdapter.setDataList(dataSource);
        }));
    }

    private void initView() {
        _mListDataAdapter = new MyListDataAdapter(getContext());
        _initListView(_mListDataAdapter);
    }

    private void _initListView(MyListDataAdapter adapterParam){

        binding.lRecyclerView.setAdapter(new LRecyclerViewAdapter(adapterParam));
        binding.lRecyclerView.setHasFixedSize(true);
        binding.lRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.lRecyclerView.setPullRefreshEnabled(true);
        binding.lRecyclerView.setArrowImageView(R.drawable.pulltorefresh_pulldown_refresh);
        //设置底部加载文字提示
        binding.lRecyclerView.setFooterViewHint(getResources().getString(R.string.try_loading), getResources().getString(R.string.no_more_data), getResources().getString(R.string.no_network));
        binding.lRecyclerView.setRefreshProgressStyle(23);
        binding.lRecyclerView.setLoadingMoreProgressStyle(23);
        binding.lRecyclerView.refresh();
        binding.lRecyclerView.setOnRefreshListener(() -> {
            //下拉刷新操作
            _pageIndex = 1;
            getListDataFromServer();
        });
        binding.lRecyclerView.setOnLoadMoreListener(() -> {
            if (adapterParam.getItemCount() < TOTAL_COUNTER) {
                //上拉加载
                _pageIndex++;
                getListDataFromServer();
            } else {
                //没有更多了
                binding.lRecyclerView.setNoMore(true);
            }
        });
    }


    private class MyListDataAdapter extends ListBaseAdapter<ProjectListModel.ProjectModel> {

        public MyListDataAdapter(Context context) {
            super(context);
        }

        @Override
        public int getItemCount() {
            return mDataList.size();
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_project_cell;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            ProjectListModel.ProjectModel projectModel = mDataList.get(position);

            TextView projNameValTV = holder.getView(R.id.tv_proj_name);
            TextView projLeaderValTV = holder.getView(R.id.tv_proj_leader_val);
            TextView projTypeValTV = holder.getView(R.id.tv_proj_type_val);
            TextView projMemberValTV = holder.getView(R.id.tv_proj_member_val);
            TextView projCreatetimeValTV = holder.getView(R.id.tv_proj_createtime_val);

            projNameValTV.setText(projectModel.getProjectName());

            projLeaderValTV.setText(StringUtils.getStrWithList("、", projectModel.getProjectChargeList(), ProjectMemberListModel.ProjectMemberModel::getMemberUserName));

            projTypeValTV.setText(Enums.ProjTypeGrade1.getValueByKey(projectModel.getProjectTypeGrade1()) + " " + Enums.ProjTypeGrade2.getValueByKey(projectModel.getProjectTypeGrade2()));

            projMemberValTV.setText(StringUtils.getStrWithList("、", projectModel.getProjectMemberList(), ProjectMemberListModel.ProjectMemberModel::getMemberUserName));

            projCreatetimeValTV.setText(DateUtil.getDateToString(projectModel.getCreateTime(), "yyyy-MM-dd"));


            //行点击监听事件
            holder.itemView.setOnClickListener(view -> {
                Intent intent = new Intent(getActivity(), ProjectEditActivity.class);
                PresentValue<ProjectListModel.ProjectModel> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.VIEW, projectModel);
                intent.putExtra(Constants.PRESENT_VALUE, presentValue);
                /*startActivity(intent);*/
                startActivityForResult(intent, PreferincesContext.REQUEST_CODE);
            });

            //任务点击
            holder.getView(R.id.bt_task).setOnClickListener((view)->{
                Intent intent = new Intent(getActivity(), TaskIndexActivity.class);
                PresentValue<Object> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.VIEW, projectModel);
                intent.putExtra(Constants.PRESENT_VALUE, presentValue);
                /*startActivity(intent);*/
                startActivityForResult(intent, PreferincesContext.REQUEST_CODE);
            });
        }
    }


    @OnClick({R.id.btn_Add_Something})
    public void onViewClicked(View view) {
        BottomShowDialog dialog = new BottomShowDialog(getActivity(), R.style.transparentFrameWindowStyle, null, null, this::linkToSomethingAdd);
        dialog.show();
    }

    private void linkToSomethingAdd(int position){
        switch (position){
            case BottomShowDialog.CLICK_BTN_ADD_PROJ: {
                Intent intent = new Intent(getActivity(), ProjectEditActivity.class);
                PresentValue<Object> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.ADD, new ProjectListModel.ProjectModel());
                intent.putExtra(Constants.PRESENT_VALUE, presentValue);
                /*startActivitylaunch.launch(intent);*/
                startActivityForResult(intent, PreferincesContext.REQUEST_CODE);
                break;
            }
            case BottomShowDialog.CLICK_BTN_ADD_TASK: {
//                Intent intent = new Intent(getActivity(), BottomShowSelectProject.class);
//                PresentValue<Object> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.ADD, null);
//                intent.putExtra(Constants.PRESENT_VALUE, presentValue);
//                startActivityForResult(intent, PreferincesContext.REQUEST_CODE);
                BottomShowSelectProject dialog = new BottomShowSelectProject(getActivity(), R.style.transparentFrameWindowStyle, null, null);
                dialog.show();
                break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG,"application fragment is on result...");

        if (resultCode == RESULT_OK){
            _pageIndex = 1;
            binding.lRecyclerView.setNoMore(false);
            getListDataFromServer();
        }
    }
}
